import { Button, View } from "@tarojs/components"
import Taro, { useRouter, useDidShow } from "@tarojs/taro"
import React, { useEffect, useState } from "react"
import clsx from "clsx"
import styles from "./index.module.css"

type IMiniInfo = {
  appId?: string
  path?: string
  miniName?: string
}
const Transfer: React.FC = function () {
  const router = useRouter()
  const [miniInfo, setMiniInfo] = useState<IMiniInfo>({
    miniName: "第三方小程序"
  })
  useDidShow(() => {
    Taro.hideHomeButton()
  })
  useEffect(() => {
    checkGaokaoSchema()
  }, [])
  function checkGaokaoSchema() {
    const query = router.params
    if (!query) return
    // 解析高考进入参数
    let keyField = Object.keys(query).find(key => {
      return decodeURIComponent(key).includes("from=gaokao")
    })
    const _query = {} as any
    if (keyField) {
      keyField = decodeURIComponent(keyField)
      keyField.split("&").reduce((prev, next) => {
        const [key, val] = next.split("=")
        prev[key] = val
        return prev
      }, _query)
    }
    console.log("transfer 页面参数: _query", _query)
    if (!_query.from || _query.from !== "gaokao") return
    // 高考工具小程序查询点击进入
    if (_query.appId) {
      setMiniInfo({
        appId: _query.appId,
        path: _query.path,
        miniName: _query.miniName
      })
    }
  }
  function handleJumpMini() {
    const { appId, path } = miniInfo
    if (appId) {
      Taro.navigateToMiniProgram({
        path,
        appId,
        fail(res) {
          // 点击取消
          if (/cancel/i.test(res.errMsg)) {
            Taro.exitMiniProgram()
          } else {
            console.log("navigateToMiniProgram跳转失败:", res)
            Taro.showToast({
              title: "跳转失败:" + res.errMsg,
              icon: "none"
            })
          }
        }
      })
    } else {
      Taro.showModal({
        title: "跳转失败",
        content: "没有跳转的小程序",
        showCancel: false,
        success() {
          Taro.exitMiniProgram()
        }
      })
    }
  }
  return (
    <View className={clsx("page", styles.transfer)}>
      <View className={styles.tip}>即将打开{miniInfo.miniName}, 请点击确认</View>
      <Button type="primary" className={styles.btn} onClick={handleJumpMini}>
        点击前往
      </Button>
    </View>
  )
}
export default Transfer
